﻿using System.Collections;
using Microsoft.SPOT;

using GT = Gadgeteer;
using GHI.Premium.Net;
using Gadgeteer.Modules.DigitalInteractionGroup;
using Gadgeteer.Modules.GHIElectronics;

namespace Gadgeteer.Modules.DigitalInteractionGroup
{
    public partial class Program
    {
        //reference of OSC module.
        OSC osc;

        // This method is run when the mainboard is powered up or reset.   
        void ProgramStarted()
        {

            //SETUP NETWORKING
            Debug.Print("Program Started");
            ethernet_J11D.Interface.Open();
            NetworkInterfaceExtension.AssignNetworkingStackTo(ethernet_J11D.Interface);
            ethernet_J11D.Interface.NetworkInterface.EnableDhcp();
            ethernet_J11D.Interface.NetworkAddressChanged += new GHI.Premium.Net.NetworkInterfaceExtension.NetworkAddressChangedEventHandler(Interface_NetworkAddressChanged);
        }

        //When network is available.
        void Interface_NetworkAddressChanged(object sender, EventArgs e)
        {
            //print our IP address
            Debug.Print("Address: " + ethernet_J11D.Interface.NetworkInterface.IPAddress);

            //Create a new OSC module.
            osc = new OSC();


            //start an OSC receiver
            osc.StartReceiver(8001);
            //event when any packet is recevied
            osc.PacketReceived += new OSC.OSCPacketEventHandler(osc_PacketReceived);
            //handler for a specific message address
            var handler = osc.AddHandler("/message/test/2");
            handler.PacketReceived += new OSC.OSCPacketEventHandler(handler_PacketReceived);


            //Starts OSC transmitter
            osc.StartTransmitter("192.168.1.101", 8000);


            //starts a timer to transmit OSC packet every second.
            GT.Timer t = new GT.Timer(1000);
            t.Tick += new GT.Timer.TickEventHandler(t_Tick);
            t.Start();
        }

        void handler_PacketReceived(OSC sender, string address, ArrayList data)
        {
            Debug.Print("LED Flash Packet Received: " + address);
            //FLASH LED HERE
        }

        void osc_PacketReceived(OSC sender,string address, ArrayList data)
        {
            Debug.Print("Received: "+address);
            foreach (var i in data)
            {
                Debug.Print(i.ToString());
            }
        }

        void t_Tick(GT.Timer timer)
        {
            osc.SendMessage("/show/a/square", -5, -1.23f,"test",new byte[] {1,2,3,4});
        }
    }
}
